<?php


namespace app\app\controller;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class State extends Base
{
    public $accessKeyId = "LTAI4G5dGuDFgvzjm8wSqReQ";
    public $accessKeySecret = "JSyjc0KA3o1aesHivcuDUZoQicXJJe";
    public $checkTime = 600;//目前检测十分钟内的上报数据
    public $showTime = 60;//目前读取1分钟内的上报数据

    function posturl($url,$data){
        $data  = json_encode($data);    
        $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        
        // db('tt')->insert([
        //     'tt' => $output
        // ]);
        curl_close($curl);
        return json_decode($output,true);
    }

    public function collectDataOld()
    {
        $data = input();

        $time = time();
        $data = $this->unsetData($data, ['pagename', '_ajax']);

        $ip = get_client_ip(0, true);
        $data['ip'] = $ip;
//            if($data['device_id']==='31F0E05A-C7FD-4CBA-995C-226C9F3C9037'){
//                $data['device_id']='31F0E05A-C7FD-4CBA-995C-226C9F3C9037-2';
//            }
        if (empty($data['x']) || empty($data['y'])) {
            $cityInfo = db('state')->where('device_id', $data['device_id'] ?: '')->where('ip', $ip)->order('id', 'desc')->find();
            if (empty($cityInfo)) {

//                    dump("ipInfo is null");
                $ipInfo = $this->getIpInfo($ip);
                if($ipInfo===false){
                    $ipInfo=[
                        'sheng'=>'',
                        'shi'=>'',
                        'x'=>0,
                        'y'=>0,
                    ];
                }
                $cityInfo = [];
                $cityInfo['sheng'] = $ipInfo['sheng'];
                $cityInfo['shi'] = $ipInfo['shi'];
                if ($ipInfo['x'] > 0) {
                    $cityInfo['x'] = $ipInfo['x'] + (-0.2 + (0.4 * rand(1000, 9999)) / 10000);
                }
                if ($ipInfo['y']) {
                    $cityInfo['y'] = $ipInfo['y'] + (-0.2 + (0.4 * rand(1000, 9999)) / 10000);
                }
            }
        } else {
            $cityInfo = db('state')->where('x', $data['y'])->where('y', $data['x'])->order('id', 'desc')->find();
            if (empty($cityInfo)) {
//                dump('meiyouzhaodao jingweidu');
                $cityInfo = $this->getIpInfo($ip);
                if($cityInfo===false){
                    $cityInfo=[
                        'sheng'=>'',
                        'shi'=>'',
                        'x' => $data['y'],
                        'y' => $data['x']
                    ];
                }else{
                    $cityInfo['x']=$data['y'];
                    $cityInfo['y']=$data['x'];
                }
            } else {
//                dump('meiyouzhaodao jingweidu');
                $cityInfo = [
                    'sheng' => $cityInfo['sheng'],
                    'shi' => $cityInfo['shi'],
                    'x' => $data['y'],
                    'y' => $data['x']
                ];
            }
        }
//            dump($cityInfo);exit;

        $data['sheng'] = $cityInfo['sheng'];
        $data['shi'] = $cityInfo['shi'];
        $data['x'] = $cityInfo['x'];
        $data['y'] = $cityInfo['y'];

        if (!isset($data['system_type'])) {
            if (strpos(strtolower($data['device_model']), 'iphone') !== false || strpos(
                    strtolower($data['device_model']),
                    'ipad'
                ) !== false) {
                $data['system_type'] = 'ios';
            } else {
                $data['system_type'] = 'android';
            }
        }
        if (empty($data['app_id'])) {
            $data['is_new'] = 1;
        } else {
            //确认是否新设备
            try {
                $return = db('device')->insertGetId([
                    'app_id' => $data['app_id'],
                    'app_name' => $data['app_name'],
                    'device_id' => $data['device_id'],
                    'jiguang_id' => $data['jiguang_id'],
                    'app_version' => $data['app_version'],
                    'system_type' => $data['system_type'],
                    'ip' => $ip,
                    'language' => $data['language'],
                    'sys_version' => $data['sys_version'],
                    'device_model' => $data['device_model'],
                    'device_name' => $data['device_name'],
                    'ui_mode' => $data['ui_mode'],
                    'operator' => $data['operator'],
                    'connection_type' => $data['connection_type'],
                    'version' => $data['version'],
                    'time_added' => $time,
                    'time_updated' => $time,
                    'first_ip'=>$ip
                ]);
                if ($return !== false) {
                    $data['is_new'] = 1;
                } else {
                    $data['is_new'] = 0;
                }
            } catch (\Exception $e) {
                db('device')->where('device_id', $data['device_id'])->update([
                    'app_id' => $data['app_id'],
                    'app_name' => $data['app_name'],
                    'app_version' => $data['app_version'],
                    'system_type' => $data['system_type'],
                    'jiguang_id' => $data['jiguang_id'],
                    'ip' => $ip,
                    'language' => $data['language'],
                    'sys_version' => $data['sys_version'],
                    'device_model' => $data['device_model'],
                    'device_name' => $data['device_name'],
                    'ui_mode' => $data['ui_mode'],
                    'operator' => $data['operator'],
                    'connection_type' => $data['connection_type'],
                    'time_updated' => $time,
                    'version' => $data['version'],
                ]);
                $data['is_new'] = 0;
            }
        }
//        dump($data);exit;

        //先查询 时间段内的数据
        $existData = db('state')->where('device_id', $data['device_id'])->where(
            'app_version',
            $data['app_version']
        )->where('time_updated', '>', ($time - $this->checkTime))->order('time_updated', 'desc')->find();
        if (!empty($existData)) {
            unset($data['is_new']);//保留此行 以确保新用户标记不会被覆盖
            $id = $existData['id'];
            $data['time_updated'] = $time;
            db('state')->where('id', $id)->inc('times')->update($data);
        } else {
            //插入新数据
            $data['time_added'] = $time;
            $data['time_updated'] = $time;
            if (!empty($data['app_id'])) {
                $id = db('state')->insertGetId($data);
            }
        }
        if ($data['is_new'] && !empty($data['app_id'])) {
            $appname = (isset($data['app_name']) ? $data['app_name'] : ' 未知appName ') . '[' . (isset($data['app_id']) ? $data['app_id'] : ' 未未知appId ') . ']';
            $shiyongdailixinxi = isset($data['is_proxy']) ? ($data['is_proxy'] == 1 ? '正在使用' : '未使用') : '未检测';
            $text = "语言language：" . (isset($data['language']) ? $data['language'] : ' null ') . "\n" .
                "应用IDappId：" . (isset($data['app_id']) ? $data['app_id'] : ' null ') . "\n" .
                "应用名称：" . (isset($data['app_name']) ? $data['app_name'] : ' null ') . "\n" .
                "应用版本appVersion：" . (isset($data['app_version']) ? $data['app_version'] : ' null ') . "\n" .
                "系统版本sysVersion：" . (isset($data['sys_version']) ? $data['sys_version'] : ' null ') . "\n" .
                "系统类型systemType：" . (isset($data['system_type']) ? $data['system_type'] : ' null ') . "\n" .
                "APIcloud引擎version：" . (isset($data['version']) ? $data['version'] : ' null ') . "\n" .
                "设备IDdeviceId：" . (isset($data['device_id']) ? $data['device_id'] : ' null ') . "\n" .
                "设备型号deviceModel：" . (isset($data['device_model']) ? $data['device_model'] : ' null ') . "\n" .
                "设备名称deviceName：" . (isset($data['device_name']) ? $data['device_name'] : ' null ') . "\n" .
                "设备界面uiMode：" . (isset($data['ui_mode']) ? $data['ui_mode'] : ' null ') . "\n" .
                "运营商operator：" . (isset($data['operator']) ? $data['operator'] : ' null ') . "\n" .
                "联网类型connectionType：" . (isset($data['connection_type']) ? $data['connection_type'] : ' null ') . "\n" .
                "所属地区:" . (isset($cityInfo['sheng']) ? $cityInfo['sheng'] : '获取失败') . (isset($cityInfo['shi']) ? $cityInfo['shi'] : '') . "\n" .
                "经纬度:" . (isset($cityInfo['x']) ? $cityInfo['x'] : '获取失败') . (isset($cityInfo['y']) ? (',' . $cityInfo['y']) : '') . "\n" .
                "是否使用代理:" . $shiyongdailixinxi . "\n" .
                "ip 1:" . get_client_ip() . "\n" .
                "ip 2:" . get_client_ip(0, true) . "\r\n" .
                date("Y-m-d H:i:s") . ' ' . request()->url(true) . "\r\n  https://www.ipip.net/ip/" . $ip . ".html";
            sendDingding($text, ($data['system_type']==='ios'?'苹果':'安卓') .'【' . $appname . '】新机器'. '接入');
        }
        $this->posturl("http://yingshi.acorntimes.com/app.php/state/collectData",$data);
        $this->success('统计记录成功！');
    }
    public function collectData()
    {
        $data = input();

        $time = time();
        $data = $this->unsetData($data, ['pagename', '_ajax']);

        $ip = get_client_ip(0, true);
        $data['ip'] = $ip;
//            if($data['device_id']==='31F0E05A-C7FD-4CBA-995C-226C9F3C9037'){
//                $data['device_id']='31F0E05A-C7FD-4CBA-995C-226C9F3C9037-2';
//            }
        if (empty($data['x']) || empty($data['y'])) {
            $cityInfo = db('state')->where('device_id', $data['device_id'] ?: '')->where('ip', $ip)->order('id', 'desc')->find();
            if (empty($cityInfo)) {
//                dump("cityInfo is null");
                $ipInfo = db('ip')->where('ip', $ip)->find();
                if (empty($ipInfo)) {
//                    dump("ipInfo is null");
                    $ipInfo = [];
                    $address = file_get_contents(
                        'http://api.map.baidu.com/location/ip?ak=a222GQqXLhLr3hqvSFA1Dz3E&ip=' . $ip . '&coor=bd09ll'
                    );

                    $address = json_decode($address, true);
                    if (isset($address['content']) && isset($address['content']['address_detail'])) {
                        $ipInfo['sheng'] = $address['content']['address_detail']['province'];
                        $ipInfo['shi'] = $address['content']['address_detail']['city'];
                        $ipInfo['x'] = $address['content']['point']['x'];
                        $ipInfo['y'] = $address['content']['point']['y'];
                        $ipInfo['guo']=!empty($address['content']['address_detail']['province'])?'中国':'';
                        $ipInfo['guo_code']=!empty($address['content']['address_detail']['province'])?'CN':'';
                    } else {
                        $ipInfo = [];
                    }
                    $ipInfo['ip'] = $ip;
                    try {
                        db('ip')->insert($ipInfo);
                    }catch (\Exception $e){

                    }
                }
                $cityInfo = [];
                $cityInfo['sheng'] = $ipInfo['sheng'];
                $cityInfo['shi'] = $ipInfo['shi'];
                if ($ipInfo['x'] > 0) {
                    $cityInfo['x'] = $ipInfo['x'] + (-0.2 + (0.4 * rand(1000, 9999)) / 10000);
                }
                if ($ipInfo['y']) {
                    $cityInfo['y'] = $ipInfo['y'] + (-0.2 + (0.4 * rand(1000, 9999)) / 10000);
                }
            }
        } else {
            $cityInfo = db('state')->where('x', $data['y'])->where('y', $data['x'])->order('id', 'desc')->find();
            if (empty($cityInfo)) {
//                dump('meiyouzhaodao jingweidu');
                $address = file_get_contents(
                    'http://api.map.baidu.com/reverse_geocoding/v3/?language=zh-CN&ak=a222GQqXLhLr3hqvSFA1Dz3E&output=json&coordtype=wgs84ll&location=' . $data['x'] . ',' . $data['y']
                );
                $address = json_decode($address, true);
//                dump($address);
                if (isset($address['result']) && isset($address['result']['addressComponent'])) {
                    $cityInfo = [
                        'sheng' => $address['result']['addressComponent']['province'],
                        'shi' => $address['result']['addressComponent']['city'],
                        'x' => $data['y'],
                        'y' => $data['x']
                    ];
                } else {
                    $cityInfo=[
                        'sheng'=>'',
                        'shi'=>'',
                        'x' => $data['y'],
                        'y' => $data['x']
                    ];
                }
            } else {
//                dump('meiyouzhaodao jingweidu');
                $cityInfo = [
                    'sheng' => $cityInfo['sheng'],
                    'shi' => $cityInfo['shi'],
                    'x' => $data['y'],
                    'y' => $data['x']
                ];
            }
        }
//            dump($cityInfo);exit;

        $data['sheng'] = $cityInfo['sheng'];
        $data['shi'] = $cityInfo['shi'];
        $data['x'] = $cityInfo['x'];
        $data['y'] = $cityInfo['y'];

        if (!isset($data['system_type'])) {
            if (strpos(strtolower($data['device_model']), 'iphone') !== false || strpos(
                    strtolower($data['device_model']),
                    'ipad'
                ) !== false) {
                $data['system_type'] = 'ios';
            } else {
                $data['system_type'] = 'android';
            }
        }
        if (empty($data['app_id'])) {
            $data['is_new'] = 1;
        } else {
            //确认是否新设备
            try {
                $return = db('device')->insertGetId([
                    'app_id' => $data['app_id'],
                    'app_name' => $data['app_name'],
                    'device_id' => $data['device_id'],
                    'jiguang_id' => $data['jiguang_id'],
                    'app_version' => $data['app_version'],
                    'system_type' => $data['system_type'],
                    'ip' => $ip,
                    'language' => $data['language'],
                    'sys_version' => $data['sys_version'],
                    'device_model' => $data['device_model'],
                    'device_name' => $data['device_name'],
                    'ui_mode' => $data['ui_mode'],
                    'operator' => $data['operator'],
                    'connection_type' => $data['connection_type'],
                    'version' => $data['version'],
                    'time_added' => $time,
                    'time_updated' => $time,
                    'first_ip'=>$ip
                ]);
                if ($return !== false) {
                    $data['is_new'] = 1;
                } else {
                    $data['is_new'] = 0;
                }
            } catch (\Exception $e) {
                db('device')->where('device_id', $data['device_id'])->update([
                    'app_id' => $data['app_id'],
                    'app_name' => $data['app_name'],
                    'app_version' => $data['app_version'],
                    'system_type' => $data['system_type'],
                    'jiguang_id' => $data['jiguang_id'],
                    'ip' => $ip,
                    'language' => $data['language'],
                    'sys_version' => $data['sys_version'],
                    'device_model' => $data['device_model'],
                    'device_name' => $data['device_name'],
                    'ui_mode' => $data['ui_mode'],
                    'operator' => $data['operator'],
                    'connection_type' => $data['connection_type'],
                    'time_updated' => $time,
                    'version' => $data['version'],
                ]);
                $data['is_new'] = 0;
            }
        }
//        dump($data);exit;

        //先查询 时间段内的数据
        $existData = db('state')->where('device_id', $data['device_id'])->where(
            'app_version',
            $data['app_version']
        )->where('time_updated', '>', ($time - $this->checkTime))->order('time_updated', 'desc')->find();
        if (!empty($existData)) {
            unset($data['is_new']);//保留此行 以确保新用户标记不会被覆盖
            $id = $existData['id'];
            $data['time_updated'] = $time;
            db('state')->where('id', $id)->inc('times')->update($data);
        } else {
            //插入新数据
            $data['time_added'] = $time;
            $data['time_updated'] = $time;
            if (!empty($data['app_id'])) {
                $id = db('state')->insertGetId($data);
            }
        }
        if ($data['is_new'] && !empty($data['app_id'])) {
            $appname = (isset($data['app_name']) ? $data['app_name'] : ' 未知appName ') . '[' . (isset($data['app_id']) ? $data['app_id'] : ' 未未知appId ') . ']';
            $shiyongdailixinxi = isset($data['is_proxy']) ? ($data['is_proxy'] == 1 ? '正在使用' : '未使用') : '未检测';
            $text = "语言language：" . (isset($data['language']) ? $data['language'] : ' null ') . "\n" .
                "应用IDappId：" . (isset($data['app_id']) ? $data['app_id'] : ' null ') . "\n" .
                "应用名称：" . (isset($data['app_name']) ? $data['app_name'] : ' null ') . "\n" .
                "应用版本appVersion：" . (isset($data['app_version']) ? $data['app_version'] : ' null ') . "\n" .
                "系统版本sysVersion：" . (isset($data['sys_version']) ? $data['sys_version'] : ' null ') . "\n" .
                "系统类型systemType：" . (isset($data['system_type']) ? $data['system_type'] : ' null ') . "\n" .
                "APIcloud引擎version：" . (isset($data['version']) ? $data['version'] : ' null ') . "\n" .
                "设备IDdeviceId：" . (isset($data['device_id']) ? $data['device_id'] : ' null ') . "\n" .
                "设备型号deviceModel：" . (isset($data['device_model']) ? $data['device_model'] : ' null ') . "\n" .
                "设备名称deviceName：" . (isset($data['device_name']) ? $data['device_name'] : ' null ') . "\n" .
                "设备界面uiMode：" . (isset($data['ui_mode']) ? $data['ui_mode'] : ' null ') . "\n" .
                "运营商operator：" . (isset($data['operator']) ? $data['operator'] : ' null ') . "\n" .
                "联网类型connectionType：" . (isset($data['connection_type']) ? $data['connection_type'] : ' null ') . "\n" .
                "所属地区:" . (isset($cityInfo['sheng']) ? $cityInfo['sheng'] : '获取失败') . (isset($cityInfo['shi']) ? $cityInfo['shi'] : '') . "\n" .
                "经纬度:" . (isset($cityInfo['x']) ? $cityInfo['x'] : '获取失败') . (isset($cityInfo['y']) ? (',' . $cityInfo['y']) : '') . "\n" .
                "是否使用代理:" . $shiyongdailixinxi . "\n" .
                "ip 1:" . get_client_ip() . "\n" .
                "ip 2:" . get_client_ip(0, true) . "\r\n" .
                date("Y-m-d H:i:s") . ' ' . request()->url(true) . "\r\n  https://www.ipip.net/ip/" . $ip . ".html";
            sendDingding($text, ($data['system_type']==='ios'?'苹果':'安卓') .'【' . $appname . '】新机器'. '接入');
        }
        $this->posturl("http://yingshi.acorntimes.com/app.php/state/collectData",$data);
        //计算观影数量和赛事数量
        $vodNum = db('openadlog')->where('app_id',$data['app_id'])->where('device_id',$data['device_id'])->whereNotNull('vod_id')->count('distinct vod_id')?:0;
        $zhiboNum = db('openadlog')->where('app_id',$data['app_id'])->where('device_id',$data['device_id'])->whereNotNull('zhibo_id')->count('distinct zhibo_id')?:0;
        db('device')->where('app_id',$data['app_id'])->where('device_id',$data['device_id'])->update([
            'vod_num'=>$vodNum,
            'zhibo_num'=>$zhiboNum,
        ]);
        $this->success('统计记录成功！');
    }
    public function unsetData($data, $keys = [])
    {
        if (!empty($keys)) {
            foreach ($keys as $key) {
                if (isset($data[$key])) {
                    unset($data[$key]);
                }
            }
        }
        return $data;
    }
//    time_updated` int(11) DEFAULT NULL COMMENT '持续一段时间访问时最后一次更新时间',
//  `time_added` int(11) DEFAULT NULL COMMENT '记录添加时间',
//  `device_id` varchar(255) NOT NULL COMMENT '设备唯一标识',
//  `system_type` varchar(32) NOT NULL COMMENT '设备类型 ios android',
//  `times` int(11) DEFAULT '0' COMMENT '总访问次数',
//  `ip` varchar(32) DEFAULT NULL,
//  `language` varchar(32) DEFAULT NULL COMMENT '手机使用语言',
//  `app_version` varchar(32) DEFAULT NULL COMMENT '应用版本',
//  `sys_version` varchar(32) DEFAULT NULL COMMENT '操作系统版本',
//  `version` varchar(32) DEFAULT NULL COMMENT 'APIcloud引擎版本',
//  `device_model` varchar(32) DEFAULT NULL COMMENT '设备型号',
//  `device_name` varchar(128) DEFAULT NULL COMMENT '设备名称',
//  `ui_mode` varchar(32) DEFAULT NULL COMMENT '设备界面',
//  `operator` varchar(32) DEFAULT NULL COMMENT '操作系统',
//  `connection_type` varchar(32) DEFAULT NULL COMMENT '联网方式',
//  `sheng` varchar(255) DEFAULT NULL COMMENT '省',
//  `shi` varchar(255) DEFAULT NULL COMMENT '市',
//  `x` varchar(16) DEFAULT '0' COMMENT '经度',
//  `y` varchar(16) DEFAULT '0' COMMENT '纬度',
//  `is_new` tinyint(

    public function showMap()
    {
        $sql = "SELECT * from (SELECT
	device_id,
	app_id,
	app_name,
	device_name,
	sum( times ) AS times,
	system_type,
	device_model,
	ui_mode,
	version,
	sys_version,
	app_version,
	LANGUAGE,
	operator,
	ip,
	connection_type,
	x,
	y,
	sheng,
	shi,
	max( is_new ) AS is_new ,
	MIN(time_added) as time_added,
	max(time_updated) as time_updated
FROM
	`mac_state` 
WHERE
	`time_added` >= " . strtotime('today')
//            ." AND    `app_id` <> 'A6158795457051'" //除去人人影迷聚集地
            . " GROUP BY
	`device_id` ) as tt
	WHERE time_updated >= " . (time() - $this->showTime);
        $list = db('state')->query($sql);
//             echo (db('state')->getLastSql());
        foreach ($list as $key => $item) {
            if (empty($item['app_id'])) {
                unset($list[$key]);
            }
            $item['time_updated_text'] = date('Y-m-d', $item['time_updated']);
            $item['time_added_text'] = date('Y-m-d', $item['time_added']);
        }
        //处理统计 今日iOS设备数 Android设备数 新用户数 老用户数
        $timeStart = strtotime('today');
        $sql = "SELECT COUNT(1) AS num,sum(ios) AS isoSum,sum(android) AS androidSum,sum(is_new) AS is_new,SUM(is_newios) AS newIosSum,sum(is_newandroid) AS newAndroidSum FROM (
SELECT device_id,max(is_new) AS is_new,CASE WHEN system_type='ios' THEN 1 ELSE 0 END AS ios,CASE WHEN system_type='android' THEN 1 ELSE 0 END AS android,CASE WHEN system_type='ios' AND is_new=1 THEN 1 ELSE 0 END AS is_newios,CASE WHEN system_type='android' AND is_new=1 THEN 1 ELSE 0 END AS is_newandroid FROM mac_state WHERE (time_updated> " . ($timeStart - 1) . " )  AND    `app_id` <> 'A6158795457051'  GROUP BY device_id) AS tt";
        $countDevice = db('state')->query($sql);

//        $sql = "SELECT COUNT(1) as num,sum(ios) as isoSum,sum(android) as androidSum,sum(is_new) as is_new from  (SELECT device_id,max(is_new) as is_new,CASE WHEN system_type='ios' THEN 1	ELSE 0 END AS ios,CASE WHEN system_type='android' THEN 1	ELSE 0 END  as android  from mac_state  WHERE  app_id <> 'A6158795457051' GROUP BY device_id ) as tt";
        $totalCount = db('state')->query("SELECT COUNT(DISTINCT device_id) as num  FROM mac_state  WHERE    app_id != 'A6158795457051'");


        $apps = db('banben')->cache('apps_tongji_sort_app', 3600)->where('display', 1)->field('appname as app_name,keyname,app_id')->order('sort', 'asc')->select();
        $tongji = [];
        foreach ($apps as $app) {
            if (!isset($tongji[$app['keyname']])) {
                $tongji[$app['keyname']] = [];
            }
            $tongji[$app['keyname']]['jinriNum'] = db('device')->where('app_id', $app['app_id'])->whereTime('time_added', 'today')->count() ?: 0;
            $tongji[$app['keyname']]['allNum'] = db('device')->where('app_id', $app['app_id'])->count() ?: 0;
        }
        usort($apps, function ($a, $b) use ($tongji) {
            if ($tongji[$a['keyname']]['jinriNum'] < $tongji[$b['keyname']]['jinriNum']) {
                return 1;
            } elseif ($tongji[$a['keyname']]['jinriNum'] > $tongji[$b['keyname']]['jinriNum']) {
                return -1;
            } else {
                return 0;
            }
        });


        //今日
        $adTodayCount = db('openadlog')->where('memo', '广告关闭')->whereTime('ctime', 'today')->count();
        $adTodayKaipingCount = db('openadlog')->where('memo', '广告关闭')->where('adtype', 1)->whereTime('ctime', 'today')->count();
        $adTodayQuanpingCount = db('openadlog')->where('memo', '广告关闭')->where('adtype', 2)->whereTime('ctime', 'today')->count();
        $adTodayJiliCount = db('openadlog')->where('memo', '广告关闭')->where('adtype', 4)->whereTime('ctime', 'today')->count();
        //昨日
        $adYesterdayCount = db('openadlog')->where('memo', '广告关闭')->whereTime('ctime', 'yesterday')->count();
        $adYesterdayKaipingCount = db('openadlog')->where('memo', '广告关闭')->where('adtype', 1)->whereTime('ctime', 'yesterday')->count();
        $adYesterdayQuanpingCount = db('openadlog')->where('memo', '广告关闭')->where('adtype', 2)->whereTime('ctime', 'yesterday')->count();
        $adYesterdayJiliCount = db('openadlog')->where('memo', '广告关闭')->where('adtype', 4)->whereTime('ctime', 'yesterday')->count();

        //前日
        //得到前天的时间
        $startBeforeYesterday = strtotime('yesterday  -1 day');
        $endBeforeYesterday = strtotime('yesterday') - 1;
        $adBeforeYesterdayCount = db('openadlog')->where('memo', '广告关闭')->whereTime('ctime', 'between', [$startBeforeYesterday, $endBeforeYesterday])->count();
        $adBeforeYesterdayKaipingCount = db('openadlog')->where('memo', '广告关闭')->where('adtype', 1)->whereTime('ctime', 'between', [$startBeforeYesterday, $endBeforeYesterday])->count();
        $adBeforeYesterdayQuanpingCount = db('openadlog')->where('memo', '广告关闭')->where('adtype', 2)->whereTime('ctime', 'between', [$startBeforeYesterday, $endBeforeYesterday])->count();
        $adBeforeYesterdayJiliCount = db('openadlog')->where('memo', '广告关闭')->where('adtype', 4)->whereTime('ctime', 'between', [$startBeforeYesterday, $endBeforeYesterday])->count();


        return json(['list' => array_values($list), 'count' => $countDevice[0], 'totalCount' => $totalCount[0]['num'], 'apps' => $apps, 'appTongji' => $tongji, 'ad' => [
            "adTodayCount" => $adTodayCount,
            "adTodayJiliCount" => $adTodayJiliCount,
            "adTodayKaipingCount" => $adTodayKaipingCount,
            "adTodayQuanpingCount" => $adTodayQuanpingCount,
            "adYesterdayCount" => $adYesterdayCount,
            "adYesterdayJiliCount" => $adYesterdayJiliCount,
            "adYesterdayKaipingCount" => $adYesterdayKaipingCount,
            "adYesterdayQuanpingCount" => $adYesterdayQuanpingCount,
            "adBeforeYesterdayCount" => $adBeforeYesterdayCount,
            "adBeforeYesterdayJiliCount" => $adBeforeYesterdayJiliCount,
            "adBeforeYesterdayKaipingCount" => $adBeforeYesterdayKaipingCount,
            "adBeforeYesterdayQuanpingCount" => $adBeforeYesterdayQuanpingCount
        ]]);
    }


//        public function fixedIpPos(){
////            $list = db('state')->where('x','<',80)->where('sheng is not null')->group('device_id,ip')->select();
//
//            $list = db()->query('SELECT * FROM `mac_state` WHERE  `x` < 70  AND   sheng is not null  GROUP BY device_id,ip');
//            dump($list);
//
//            dump(db('state')->getLastSql());
//            foreach ($list as $item){
//                $ip = $item['ip'];
//                dump($ip);
//                $ipInfo = db('ip')->where('ip',$ip)->find();
//                if(empty($ipInfo)) {
//                    dump("ipInfo is null");
//                    $ipInfo = [];
//                    $address = file_get_contents(
//                        'http://api.map.baidu.com/location/ip?ak=a222GQqXLhLr3hqvSFA1Dz3E&ip='.$ip.'&coor=bd09ll'
//                    );
//
//                    $address = json_decode($address, true);
//                    if (isset($address['content']) && isset($address['content']['address_detail'])) {
//                        $ipInfo['sheng'] = $address['content']['address_detail']['province'];
//                        $ipInfo['shi'] = $address['content']['address_detail']['city'];
//                        $ipInfo['x'] = $address['content']['point']['x'] ;
//                        $ipInfo['y'] = $address['content']['point']['y'];
//                    }else{
//                        $ipInfo=[];
//                    }
//                    $ipInfo['ip']=$ip;
//                    db('ip')->insert($ipInfo);
//                }
//                $cityInfo=[];
//                $cityInfo['sheng'] = $ipInfo['sheng'];
//                $cityInfo['shi'] = $ipInfo['shi'];
//                if($ipInfo['x']>0) {
//                    $cityInfo['x'] = $ipInfo['x'] + (-0.2 + (0.4 * rand(1000, 9999)) / 10000);
//                }
//                if($ipInfo['y']) {
//                    $cityInfo['y'] = $ipInfo['y'] + (-0.2 + (0.4 * rand(1000, 9999)) / 10000);
//                }
//
//                db('state')->where('device_id',$item['device_id'])->where('ip',$ip)->update(['x'=>$cityInfo['x']]);
//                dump(db('state')->getLastSql());
//            }
//
//
//        }
    public function fixedIsNew()
    {
        $page = input('page', 0, 'intval');
        if ($page < 1) {
            $page = 1;
        }
        $list = db('state')->group('device_id')->order('time_added', 'asc')->paginate(300);
        dump(db('state')->getLastSql());
        $items = $list->items();
        foreach ($items as $item) {
            $newItem = [];
            //如果is_new 不等于1 则设置为1
            if ($item['is_new'] < 1) {
                db('state')->where('id', $item['id'])->update(['is_new' => 1]);
            } else {
                db('state')->where('id', 'neq', $item['id'])->where('device_id', $item['device_id'])->update(
                    ['is_new' => 0]
                );
            }
        }
        echo $list->render();
        if ($page < $list->lastPage()) {
            $page++;
            echo "<script>setTimeout(function (){location.href='" . url('', ['page' => $page]) . "'}, 1000 );</script>";
        } else {
            echo '处理完毕';
        }
    }

    public function checkTodayNew()
    {
        dump('今日开始时间' . strtotime('today'));
        $deviceIdAlls = db('state')->where('is_new', 1)->where('time_added', '>=', strtotime('today'))->column(
            'device_id'
        );
        dump('获取到的数据');
        dump(count($deviceIdAlls));
        $deviceIdUniques = array_unique($deviceIdAlls);
        dump('取唯一值');
        dump(count($deviceIdUniques));
//            dump('今日设备');
//            dump(count(array_intersect($deviceIdAlls, $deviceIdUniques)));
        dump('今天之前的所有设备ID');
        $deviceIds = db('state')->where('time_added', '<', strtotime('today'))->column('device_id');
        $deviceIds = array_unique($deviceIds);
        dump(count($deviceIds));
        dump('重复的设备IDs');
        dump(array_intersect($deviceIdUniques, $deviceIds));
        $data = db('state')->fieldRaw(
            'count(system_type) as total,sum(CASE WHEN system_type="ios" THEN 1 ELSE 0 END) as iosNum,sum(CASE WHEN system_type="android" THEN 1 ELSE 0 END) as androidNum'
        )->where('is_new', 1)->where('time_added', '>=', strtotime('today'))->select();
        //直接查询结果
        dump('今日新用户');
        dump($data[0]);
        dump('通过上面的 sql 得到今日安卓设备');
        $deviceIdAndroids = db('state')->where('system_type', 'android')->where('is_new', 1)->where('time_added', '>=', strtotime('today'))->column('device_id');
        dump(count(array_unique($deviceIdAndroids)));
        dump('通过上面的 sql 得到今日苹果设备');
        $deviceIdIoss = db('state')->where('system_type', 'ios')->where('is_new', 1)->where('time_added', '>=', strtotime('today'))->column('device_id');
        dump(count(array_unique($deviceIdIoss)));


        $sql = "SELECT * from (SELECT
	device_id,
	device_name,
	sum( times ) AS times,
	system_type,
	device_model,
	ui_mode,
	version,
	sys_version,
	app_version,
	language,
	operator,
	ip,
	connection_type,
	x,
	y,
	sheng,
	shi,
	max( is_new ) AS is_new ,
	MIN(time_added) as time_added,
	max(time_updated) as time_updated
FROM
	`mac_state` 
WHERE
	`time_added` >= " . strtotime('today') . " 
GROUP BY
	`device_id` )as tt";
        $list = db('state')->query($sql);
        $deviceIdAndroidsFromCount = [];
        $oldDeviceIdAndroidsFromCount = [];
        $deviceIdIossFromCount = [];
        $oldDeviceIdIossFromCount = [];
        dump('统计的总数据量');
        dump(count($list));
        foreach ($list as $item) {

            if ($item['system_type'] == 'ios') {
                if ($item['is_new'] == 1) {
                    $deviceIdIossFromCount[] = $item['device_id'];
                } else {
                    $oldDeviceIdIossFromCount[] = $item['device_id'];
                }
            }
            if ($item['system_type'] == 'android') {
                if ($item['is_new'] == 1) {
                    $deviceIdAndroidsFromCount[] = $item['device_id'];
                } else {
                    $oldDeviceIdAndroidsFromCount[] = $item['device_id'];
                }
            }
        }
        dump('统计数据得到的新安卓数');
        dump(count(array_unique($deviceIdAndroidsFromCount)));
        dump('统计数据得到的新苹果数');
        dump(count(array_unique($deviceIdIossFromCount)));
        dump('统计数据得到的旧安卓数');
        dump(count(array_unique($oldDeviceIdAndroidsFromCount)));
        dump('统计数据得到的旧苹果数');
        dump(count(array_unique($oldDeviceIdIossFromCount)));

        dump('安卓不同的设备');
        $androidDiff = array_diff($deviceIdAndroidsFromCount, $deviceIdAndroids);
        dump($androidDiff);
        dump('苹果不同的设备');
        $iosDiff = array_diff($deviceIdIossFromCount, $deviceIdIoss);
        dump($iosDiff);

    }

    public function showApps()
    {

    }

    public function getIpInfo($ip){
        AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessKeySecret)
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('geoip')
                // ->scheme('https') // https | http
                ->version('2020-01-01')
                ->action('DescribeIpv4Location')
                ->method('POST')
                ->host('geoip.aliyuncs.com')
                ->options([
                    'query' => [
                        'Ip' => $ip,
                    ],
                ])
                ->request();
            $resultArray = $result->toArray();

            $ipInfo = [
                'ip' => $ip,
                'x' => $resultArray['Longitude'],
                'y' => $resultArray['Latitude'],
                'sheng' => $resultArray['Province'],
                'shi' => $resultArray['City'],
                'guo' => $resultArray['Country'],
                'guo_code' => $resultArray['Country']=='局域网'?'other':$resultArray['CountryCode'],
                'from'=>'app/state/collectdata'
            ];
            //新增
            try {
                db('ip')->insert($ipInfo);
//                        dump('=====' . db('ip')->getLastSql());
            } catch (\Exception $e) {
                db('ip')->where('ip', $ip)->update($ipInfo);
//                        dump('A ===' . db('ip')->getLastSql());

            }
            return $ipInfo;
//                    dump($ipInfo);
        } catch (ClientException $e) {
            return false;
//                echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
//                echo $e->getErrorMessage() . PHP_EOL;
            return false;
        }
    }
}